package org.budo.support.javax.imageio.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

/**
 * @author li
 * @version 1 (2016年3月18日 下午1:24:21)
 * @since Java7
 */
public class ImageIoUtil {
    public static Boolean write(BufferedImage bufferedImage, String formatName, OutputStream outputStream) {
        try {
            return ImageIO.write(bufferedImage, formatName, outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static BufferedImage read(File file) {
        try {
            return ImageIO.read(file);
        } catch (IOException e) {
            throw new RuntimeException("#28 read error, file=" + file, e);
        }
    }

    public static BufferedImage read(InputStream inputStream) {
        try {
            return ImageIO.read(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("#37 read error, inputStream=" + inputStream, e);
        }
    }

    public static void writePng(BufferedImage bufferedImage, OutputStream outputStream) {
        write(bufferedImage, "png", outputStream);
    }

    public static byte[] toPng(BufferedImage bufferedImage) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        writePng(bufferedImage, outputStream);
        return outputStream.toByteArray();
    }
}